<template>
    <el-dialog
      v-model="dialogVisible"
      :destroy-on-close="true"
      :align-center="true"
      width="600px"
      title="合并支付项目费"
      style="padding: 20px"
    >
      <el-form
        ref="jobFormRef"
        :rules="rules"
        :model="dialogData.itemInfo"
        label-width="120px"
        label-suffix=" :"
      >
            <el-form-item label="支付总金额"  >
              <span class="total-amt-info">￥ {{ dialogData.itemInfo.totalAmt || "--" }}</span>
            </el-form-item>
            <el-form-item label="发票类型">
              <el-radio-group v-model="dialogData.itemInfo.invoiceType" @change="handleInvoiceTypeChange">
                <el-radio v-for="item in invoiceType" :key="item.value" :value="item.value">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="支付方式">
              <el-select
                size="large"
                style="width: 100%"
                v-model="dialogData.itemInfo.payType"
                placeholder="支付方式"
              >
                <el-option v-for="item in PayTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <div class="payinfo-box">
                  <!-- <div class="payitem-box" v-for="(item,index) in dialogData.payItems" :key="index">
                    <div class="amt-info">￥ {{ item.payAmt }}</div>
                    <div class="note-info">{{ item.note }}</div>
                  </div> -->
                  <el-table :data="dialogData.tableData" style="width: 100%">
                    <el-table-column type="index" width="50" />
                    <el-table-column label="岗位" prop="jobTitle" >
                    </el-table-column>
                    <el-table-column label="金额" prop="totalAmt" width="100"></el-table-column>
                    <el-table-column label="明细" prop="items" type="expand" width="80">
                      <template #default="scope">
                        <div class="job-items-box">
                          <div class="item-box" v-for="(item,index) in scope.row.items" :key="index">
                            <span class="title-info">{{ item.note }}</span>
                            <span class="amt-info">{{ item.payAmt }}</span>
                          </div> 
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" align="right" width="80">
                      <template #default="scope">
                        <el-button size="small" type="danger" @click="handleDelete(scope.$index)"> 删除 </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
            </div>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button size="large" type="primary" @click="handleSubmit" :loading="btnLoading">
          确认付款
        </el-button>
      </template>
    </el-dialog>
    <OfflinePayResultDialog ref="dialogRef" />
  </template>
  <script setup lang="ts">
  import { ref, reactive } from "vue";
  import { getOptTitle, OptEnum } from "@/biz/eenum/appEnum";
  import { DialogParam } from "@/biz/interface/DialogType";
  import { FlexJobPayVo } from "@/biz/interface/FlexjobType";
  import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
  import { getJobsbillApi, handleJobsPayApi} from "@/api/modules/cpyjob/pay"
  import { invoiceType, PayTypes} from "@/biz/datas/appData"
  import OfflinePayResultDialog from "../../comm/jobdetail/components/OfflinePayResultDialog.vue";
  import { filterEnum } from "@/utils";
  //页面的数据
  interface flexjobAbnormalDialogOption extends DialogParam {
    //弹出表单的标题
    title: string;
    // // 支付明细
    // payItems:[];
    // 要支付的岗位
    ids:[],
    // 需要支付的岗位的费用明细
    tableData:[],
    //当前的数据对象
    itemInfo: FlexJobPayVo;
    //其它的数据都继续在这里加
  }
  //提交按钮，避免多次提交
  const btnLoading = ref(false);
  //弹出框的参数
  const dialogVisible = ref(false);
  //当前表单数据在这里初始化
  const dialogData = reactive<flexjobAbnormalDialogOption>({
    optType: OptEnum.UNKNOW,
    title: "",
    // payItems: [],
    ids:[],
    tableData:[],
    itemInfo: {}
  });
  
  // 接收父组件传过来的参数
  const acceptParams = (params: DialogParam): void => {
    dialogData.optType = params.optType;
    dialogData.rowData = params.rowData;
    dialogData.title = getOptTitle(dialogData.optType);
  
    if (dialogData.rowData) {
      initItemInfo();
      // 加载普票的支付信息
      handleInvoiceTypeChange(2);
      // 赋值 当前要处理所有的岗位
      dialogData.itemInfo.ids = params.rowData.ids;
      // 去查找每个岗位的支付详情
      getJobPayItemsInfo();
    }
  
    dialogVisible.value = true;
  };
  
  //初始化页面的数据
  const initItemInfo = (): void => {
    dialogData.itemInfo = { invoiceType:2, payType:4 };
  };
  
  //获取当前数据的详情，直接调用接口获取数据
  const getJobPayItemsInfo = async () => {
    if (dialogData.itemInfo.ids) {
      let res = await getJobsbillApi({ 
        jobIds: dialogData.itemInfo.ids,
        invoiceType:dialogData.itemInfo.invoiceType 
      });
      // console.log("每个岗位的支付明细", res);
      if(res && res.data){
        dialogData.tableData = res.data;
        calcPayInfo();
      }
    }
  };
  
  //数据较验
  const rules = reactive({
    title: [{ required: true, message: "异议标题不能为空", trigger: "blur" }],
    content: [{ required: true, message: "异议内容不能为空", trigger: "blur" }]
  });

  const handleInvoiceTypeChange = async (val)=>{
    let res = await getJobsbillApi({
      jobIds: dialogData.itemInfo.ids,
      invoiceType:dialogData.itemInfo.invoiceType
    });
    // console.log("获取支付明细:", val, res);
    if(res && res.data){
        dialogData.tableData = res.data;
        calcPayInfo();
    }
  }

  // 处理一下需要支付的信息
  const calcPayInfo = ()=>{
    if(dialogData.tableData){
      // 计算一下统计值
      dialogData.itemInfo.totalAmt = dialogData.tableData.reduce((sum,item)=>sum+item.totalAmt, 0);
    }
  }

// 移除一条开票明细
const handleDelete = ( idx:number ) => {
  // console.log("移除一条", idx);
  if (dialogData.tableData) {
    // 去掉一个
    dialogData.tableData.splice(idx,1);
    // 重新计算一下
    calcPayInfo();
  }
};

// 打开 支付
const dialogRef = ref();
const handleOpenPayDialog = (totalAmt,payNo) => {
  let params = {
    optType: OptEnum.EDIT,
    rowData: { totalAmt, payNo }
  };
  dialogRef.value.acceptParams(params);
};

// 提交数据（新增/编辑）
const jobFormRef = ref<FormInstance>();
const handleSubmit = () => {
  btnLoading.value = true;
  jobFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    try {
      if (dialogData.tableData) {
        //提交数据
        let jobIds = dialogData.tableData.map(item=> item.jobId);
        // console.log("要提交的岗位IDs", jobIds);
        if(jobIds && jobIds.length){
          // console.log("提交的数据", dialogData.itemInfo, dynamicTags.value);
          ElMessageBox.confirm(`确认是:${filterEnum(dialogData.itemInfo.invoiceType, invoiceType)}?`, "温馨提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            draggable: true
          }).then(async () => {
            let res = await handleJobsPayApi({
              jobIds,
              invoiceType:dialogData.itemInfo.invoiceType,
              payType: dialogData.itemInfo.payType
            });
            if (res.data) {
            if(dialogData.itemInfo.payType == 4){
                ElMessage.success({ message: `支付成功！` });
                // 线下支付，跳转到提醒信息页面
                if(res.data.payNo){
                  let totalAmt = res.data.totalAmt;
                  let payNo = res.data.payNo;

                  // 支付信息传递到信息提醒页面
                  handleOpenPayDialog(totalAmt, payNo);
                  // 都支持了，注这里就可以
                  emits("refresh-list");
                  dialogVisible.value = false;
                }
              }  else {
                ElMessage.error({message:"目前就支持线下支付."});
              }
              //刷新列表数据
              // emits("refresh-list");
              // dialogVisible.value = false;
            }
          });
        }else{
          ElMessage.error({message:"需要支付的岗位不能为空."});
        }
        // 测试用
        // handleOpenPayDialog(13645.6, "202408301542429797");
        // dialogVisible.value = false;
      }
    } catch (error) {
      // console.log("出现异常情况,", error);
    } finally {
      btnLoading.value = false;
    }
  });
};

//页面事件
const emits = defineEmits(["refresh-list"]);
  //页面参数
  defineExpose({
    acceptParams
  });
</script>
<style scoped lang="scss">
.total-amt-info{
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--el-color-danger);
}

.payinfo-box{
  width: 100%;

  .payitem-box{
    // border: 1px solid red;
    margin: 10px;

    display: flex;
    align-items: center;
    justify-content: space-between;

    .amt-info{
      font-size: 1.1rem;
      font-weight: 600;
      color: var(--el-color-info);
    }

    .note-info{
      font-size: 0.75rem;
      font-weight: 400;
      color: var(--el-color-info-light-3);
    }
  }
}

.job-items-box{
  
  display: flex;
  align-items: center;
  justify-content: center;

  .item-box{
    margin: 10px ;
    // border: 1px solid red;

    .title-info{
      font-size: 0.75rem;
      font-weight: 400;
      color: var(--el-color-info-light-3);
    }

    .amt-info{
      margin: 0 10px;
      font-size: 1.1rem;
      font-weight: 600;
      color: var(--el-color-danger);
    }
  }
}
</style>
  